<template>
  <div id="InterfaceDictDiv">
    <div class="bodyContent">
      <Splitpanes>
        <!-- 左侧表格  -->
        <Pane size="90">
          <div class="tableBody">
            <vxe-table  ref="InterfaceDictTableRef" :span-method="mergeRowMethod" @current-change="detailRowClick" border height="auto" :data="detailInfoList" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
              <vxe-column field="roleName" title="角色名称" width="200px"></vxe-column>
              <vxe-column field="itemName" title="项目名称" width="200px"></vxe-column>
              <vxe-column field="taskName" title="任务名称" ></vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <!-- 右侧表单 -->
        <Pane size="60">
          <vxe-toolbar perfect>
            <template #buttons>
              <div class="smallToolTitle">分配任务人</div>
              <vxe-button type="text" v-if="type == '2' && chkStatus != '1'" class="button-blue" icon="vxe-icon-square-plus" content="添加" :disabled="disabledTag" @click="addUserDialog()"></vxe-button>
              <vxe-button type="text"  icon="vxe-icon-delete" v-if="type == '2' && chkStatus != '1'" class="button-red" content="删除" :disabled="disabledTag" @click="handleDelete"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBox">
            <vxe-table ref="qcItemTableRef"   align="center" height="auto" :data="detailUserList" :row-config="{ isCurrent: true, isHover: true}" :column-config="{ resizable: true }" resizable show-overflow keep-source>
              <vxe-column type="checkbox" v-if="type == '2' && chkStatus != '1'" width="30" align="center"></vxe-column>
              <vxe-column field="userCode" title="用户编号" > </vxe-column>
              <vxe-column field="userName" title="用户名"> </vxe-column>
            </vxe-table>
          </div>
          <el-dialog title="用户信息" :append-to-body="false" :show-close="false" v-model="showDialog" append-to-body width="1000px" :close-on-click-modal="false" destroy-on-close v-if="showDialog">
            <vxe-toolbar perfect>
              <template #buttons>
                <vxe-input style="width: 130px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findUserList" @keyup="findUserList" @search-click="findUserList()"></vxe-input>
                <vxe-button type="text" class="button-blue" content="查询" @click="findUserList"></vxe-button>
              </template>
            </vxe-toolbar>
            <div class="tableBody" style="height: 600px">
              <vxe-table ref="labItemTableRef" class="mytable-scrollbar dialogTable" border height="520px" align="center" :data="userList" :row-config="{ keyField: 'username', isHover: true }" :column-config="{ resizable: true }" :checkbox-config="{
                  checkMethod: checCheckboxkMethod2,
                  visibleMethod: showCheckboxkMethod2,
                  checkRowKeys: defaultSelecteRowKeys
                }" resizable show-overflow keep-source>
                <vxe-column title="序号" width="80">
                  <template #default="{ row, rowIndex, column }">
                    <span>{{ rowIndex + 1 }}</span>
                  </template>
                </vxe-column>
                <vxe-column type="checkbox" width="30px"></vxe-column>
                <vxe-column field="username" title="用户编号" > </vxe-column>
                <vxe-column field="realname" title="用户名"> </vxe-column>
              </vxe-table>

              <div class="dialog-footer flex right justify-end">
                <el-button type="primary" @click="saveBacthUser('qcItemTableRef')">确定</el-button>
                <el-button @click="closeDialog('qcItemTableRef')">取消</el-button>
              </div>
            </div>
          </el-dialog>
        </Pane>
      </Splitpanes>

    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted, defineProps, watch } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import {VxeMessage, VxeNotifyType} from "@/utils/CommonMessage";
import {isEmpty} from "lodash";
import {VXETable} from "vxe-table";
let { proxy }: any = getCurrentInstance();

let disabledTag = ref(false);
let showDialog = ref(false); //添加弹框展示状态
let qcItemTableRef = ref(null);
let type = ref('');
let chkStatus = ref('');
let searchForm = reactive({
  searchValue: ''
});
let detailInfoList: any = reactive([]);
let detailsForm = reactive({
  id: null,
  detatilStatus: '',
  roleName: '',
  itemName: '',
  taskName: '',
  taskId: ''
});
let rateform = reactive({
  id: null,
  orgId: '',
  processCode: '',
  processName: '',
  versionCode: '',
  versionName: '',
  gradeCode: '',
  gradeName: '',
  status: ''
});
let detailUserList: any = reactive([]);
let userList: any = reactive([]);

defineExpose({ initPage });

function initPage(row: any) {
  Object.assign(rateform, row);
  type.value = row.type;
  chkStatus.value = row.status;
  getDetailList(row);
}
//获取明细table
function getDetailList (data: any) {
  detailInfoList.length = 0;
  const url = '/emr/processDetail/findEmrProcessDetailList?processCode='+data.processCode;
  proxy.$http
      .get(url)
      .then((res: any) => {
        detailInfoList.push(...res.data);
        detailRowClick({ row: detailInfoList[0] }); //默认选中第一条数据
      })
      .catch((err: any) => {
        proxy.$alert(err, '提示');
      });
}
//合并单元格
function mergeRowMethod({ row, _rowIndex, column, visibleData }) {
  const fields = ['roleName','itemName']
  const cellValue = row[column.field]
  if (cellValue && fields.includes(column.field)) {
    const prevRow = visibleData[_rowIndex - 1]
    let nextRow = visibleData[_rowIndex + 1]
    if (prevRow && prevRow[column.field] === cellValue) {
      return { rowspan: 0, colspan: 0 }
    } else {
      let countRowspan = 1
      while (nextRow && nextRow[column.field] === cellValue) {
        nextRow = visibleData[++countRowspan + _rowIndex]
      }
      if (countRowspan > 1) {
        return { rowspan: countRowspan, colspan: 1 }
      }
    }
  }
}
// 点击字段当前行触发的事件
function detailRowClick({ row }: any) {
  if (isEmpty(row)) {
    userList.length = 0;
    Object.assign(detailsForm, {});
  } else {
    Object.assign(detailsForm, row);
    (proxy.$refs.InterfaceDictTableRef as any).setCurrentRow(row);
    //获取处置人信息
    getDetailUserList();
  }
}
function getDetailUserList() {
  detailUserList.length = 0;
  const url = '/emr/processDetailUser/findDetailUserList';
  proxy.$http
      .get(url,  {params: {processDetailId: detailsForm.id}})
      .then((res: any) => {
        detailUserList.push(...res.data);
      })
      .catch((err: any) => {
        proxy.$alert(err, '提示');
      });
}
// 添加按钮
function addUserDialog() {
  findUserList();
  showDialog.value = true;
}
async function handleDelete() {
  const arr = (proxy.$refs.qcItemTableRef as any).getCheckboxRecords();
  if (!(arr && arr.length > 0 && arr[0])) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    const type = await VXETable.modal.confirm('确定要删除当前勾选的数据？');
    if (type === 'confirm') {
      const url = '/emr/processDetailUser/deleteDetailUserList';
      proxy.$http
          .post(url, arr)
          .then((res: any) => {
            if (res.status.code === 1) {
              getDetailUserList(); // 获取检验仪器表格数据
              VxeMessage('删除成功', VxeNotifyType.success);
            } else {
              VxeMessage(res.status.msg, VxeNotifyType.error);
            }
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
    }
  }
}

// 弹框保存的确定按钮
function saveBacthUser() {
  const selectRows = (proxy.$refs.labItemTableRef as any).getCheckboxRecords();
  if (selectRows.length > 0) {
    const addUserList = [];
    for (const sltRow of selectRows) {
      const qcitem = detailUserList.find((qc: any) => qc.userCode == sltRow.username);
      if (isEmpty(qcitem)) {
        const addQcItem = {
          processCode:rateform.processCode,
          processName:rateform.processName,
          standardTaskId:detailsForm.taskId,
          processDetailId:detailsForm.id,
          userCode:sltRow.username,
          userName:sltRow.realname
        };
        addUserList.push(addQcItem);
      }
    }
    if (addUserList.length > 0) {
      const url = '/emr/processDetailUser/addDetailUserList';
      proxy.$http
          .post(url, addUserList)
          .then((res: any) => {
            getDetailUserList();
            VxeMessage(res.status.msg, VxeNotifyType.success);
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
    } else {
      VxeMessage('请选择要添加的数据', VxeNotifyType.error);
    }
  }
  closeDialog();
}
function closeDialog() {
  showDialog.value = false;
}
// 获取用户列表
function findUserList() {
  userList.length = 0;
  const url = '/api/user/getUserInfoList?skipCount=0&maxResultCount=200&skipCount=0&maxResultCount=200&keywords='+searchForm.searchValue;
  proxy.$http
      .get(url)
      .then((res: any) => {
        userList.push(...res.data);
      })
      .catch((err: any) => {
        proxy.$alert(err, '提示');
      });
}
// 弹框 表格复选框(是否允许用户手动勾选)
let defaultSelecteRowKeys = reactive([]);
function checCheckboxkMethod2({ row }: any) {
  const obj = detailUserList.filter((p: any) => {
    defaultSelecteRowKeys.push(p.userCode)
    return p.userCode == row.username;
  });
  return obj.length == 0;
}

// 弹框 表格复选框 设置(是否显示复选框)
function showCheckboxkMethod2({ row }: any) {
  const obj = detailUserList.filter((p: any) => {
    // return p.itemDictId == row.id;
  });
  return obj.length == 0;
}
</script>

<style lang="scss" scoped>
#InterfaceDictDiv {
  height: 100%;

  .bodyContent {
    height: calc(100%);

    .splitpanes {
      background-color: $base-white;

      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }

      .right-Btn {
        margin: 0 0 0 5px;
        width: 40px;
      }

      // 右侧保存按钮
      .saveBtn {
        float: right;
        margin: 5px 10px;
      }

      .tableBody {
        height: calc(100% - 40px);
      }

      // 中间
      .tableBox {
        width: 100%;
        height: calc(100% - 40px);
      }

    }
  }
}
</style>
